#!/usr/bin/env python
# coding: utf-8

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
import logging
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# 配置日志记录
logging.basicConfig(filename='model.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 假设已经通过回归分析等方法确定了回归系数和常数项
alpha = 15  # 花期时长的回归系数，适当增大
beta = 40  # 旅游产品丰富度的回归系数，适当增大
gamma = 50  # 常数项，适当增大

# 用户输入门票价格
try:
    ticket_price = float(input("请输入门票价格（元）："))
except ValueError:
    logging.error("门票价格输入错误，请输入一个数字。")
    exit(1)

# 从数据文件中读取人均餐饮住宿消费
try:
    with open('accommodation_price.txt', 'r') as f:
        accommodation_price = float(f.read().strip())
except FileNotFoundError:
    logging.error("找不到人均餐饮住宿消费数据文件，请检查文件路径。")
    accommodation_price = 400  # 使用默认值
except ValueError:
    logging.error("人均餐饮住宿消费数据文件格式错误，请检查文件内容。")
    accommodation_price = 400  # 使用默认值

# 假设其他参数的固定值
experience_price = 180  # 旅游项目体验平均收费，适当提高
experience_rate = 0.6  # 游客参与项目体验比例，适当提高
flower_product_price = 250  # 人均花卉及相关产品消费，适当提高
deep_processing_output = 12  # 花卉深加工产业年产量（万件），适当提高
deep_processing_price = 200  # 花卉深加工产品单价（元/件），适当提高
cultural_product_sales = 15  # 文创产业产品销量（万件），适当提高
cultural_product_price = 80  # 文创产品单价（元/件），适当提高
job_creation = 500  # 新产业创造就业岗位数量（个），适当提高
avg_job_income = 5  # 平均岗位年收入（万元），适当提高
total_cost = 5  # 总成本（万元），适当降低


# 定义函数计算游客数量
def calculate_visitors(T, P):
    return alpha * T + beta * P + gamma


# 定义函数计算旅游收入
def calculate_tourism_income(N, T, P, satisfaction):
    # 考虑游客停留天数的影响
    avg_stay_days = 1 + 0.6 * P  # 旅游产品丰富度越高，停留天数可能越多
    ticket_revenue = N * ticket_price
    accommodation_revenue = N * accommodation_price * avg_stay_days
    experience_revenue = N * experience_price * experience_rate * avg_stay_days
    flower_product_revenue = N * flower_product_price * avg_stay_days
    # 引入游客满意度对消费的促进作用
    satisfaction_factor = 1 + 0.3 * satisfaction  # 满意度越高，消费提升比例越大
    total_tourism_income = (ticket_revenue + accommodation_revenue + experience_revenue + flower_product_revenue) * satisfaction_factor
    return total_tourism_income


# 定义函数计算产业带动收入
def calculate_industry_income():
    deep_processing_revenue = deep_processing_output * deep_processing_price
    cultural_product_revenue = cultural_product_sales * cultural_product_price
    return deep_processing_revenue + cultural_product_revenue


# 定义函数计算就业增收
def calculate_employment_income():
    return job_creation * avg_job_income


# 定义函数计算综合经济效益
def calculate_total_economy(tourism_income, industry_income, employment_income):
    return tourism_income + industry_income + employment_income - total_cost


# 设定参数范围
T_range = np.linspace(1, 5, 10)
P_range = np.linspace(0.1, 0.9, 10)
F_range = np.linspace(1, 5, 10)
A = 3  # 旅游活动丰富度指数

# 生成多项式特征并拟合回归模型
poly = PolynomialFeatures(degree=2)
X = np.array([T_range, P_range]).T
X_poly = poly.fit_transform(X)
model = LinearRegression()
model.fit(X_poly, calculate_visitors(T_range, P_range))

# 准备绘图数据
x_data = []
y_data = []
tourism_income_data = []
for T in T_range:
    for P in P_range:
        new_X_poly = poly.transform(np.array([[T, P]]))
        N = model.predict(new_X_poly)[0]  # 确保获取标量值
        competition_factor = random.uniform(0.8, 1.2)
        N = N * competition_factor
        # 假设游客满意度与旅游产品丰富度相关
        satisfaction = P
        tourism_income = calculate_tourism_income(N, T, P, satisfaction) / 10000
        x_data.append(T)
        y_data.append(P)
        tourism_income_data.append(tourism_income)

# 转换为numpy数组
x_data = np.array(x_data)
y_data = np.array(y_data)
tourism_income_data = np.array(tourism_income_data)

# 绘制3D散点图
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
sc = ax.scatter(
    x_data, y_data, tourism_income_data,
    c=tourism_income_data,
    cmap='viridis',
    alpha=0.8,
    s=100,
    edgecolors='w')  # 补上缺失的括号

# 设置图表标题和轴标签
ax.set_title(
    f'毕节赏花经济旅游总收入与基础设施完善程度、花卉品种多样性的关系\n'
    f'(旅游活动丰富度指数 A={A})',
    fontsize=14)
ax.set_xlabel('旅游基础设施完善程度指数 (T)', fontsize=12)
ax.set_ylabel('花卉品种多样性指数 (F)', fontsize=12)
ax.set_zlabel('旅游总收入 (亿元)', fontsize=12)

# 添加颜色条和网格
fig.colorbar(sc, ax=ax, label='旅游总收入 (亿元)')
ax.grid(True, linestyle='--', alpha=0.7)

# 优化视角
ax.view_init(elev=30, azim=45)

# 显示图表
plt.tight_layout()
plt.show()

# 计算采取措施后的经济效益
new_T = 4
new_P = 0.8
new_F = 4
new_X_poly = poly.transform(np.array([[new_T, new_P]]))
new_N = model.predict(new_X_poly)[0]
competition_factor = random.uniform(0.8, 1.2)
new_N = new_N * competition_factor
# 假设游客满意度与旅游产品丰富度相关
new_satisfaction = new_P
new_tourism_income = calculate_tourism_income(new_N, new_T, new_P, new_satisfaction) / 10000
new_industry_income = calculate_industry_income() / 10000
new_employment_income = calculate_employment_income() / 10000
new_total_economy = calculate_total_economy(new_tourism_income, new_industry_income, new_employment_income)

# 记录日志和打印结果
logging.info(f"模型运行参数: 门票价格={ticket_price}元, 人均餐饮住宿消费={accommodation_price}元")
logging.info(f"预测结果: 旅游总收入={new_tourism_income:.2f}亿元, 综合经济效益={new_total_economy:.2f}亿元")
print("\n" + "=" * 50)
print("毕节赏花经济预测模型结果")
print("=" * 50)
print(f"采取措施后旅游总收入: {new_tourism_income:.2f}亿元")
print(f"采取措施后产业带动收入: {new_industry_income:.2f}亿元")
print(f"采取措施后就业增收: {new_employment_income:.2f}亿元")
print(f"采取措施后综合经济效益: {new_total_economy:.2f}亿元")
print("=" * 50)
